<script setup lang="ts">
import { onMounted, ref } from 'vue';

import { IconifyIcon } from '@vben/icons';

import {
  Button,
  message,
  Modal,
  Pagination,
  Select,
  SelectOption,
  Spin,
  Tag,
} from 'ant-design-vue';
import dayjs from 'dayjs';

import {
  cancelBooking as cancelBookingApi,
  getMyBookings,
  takeQueueTicket as takeQueueTicketApi,
} from '#/api/booking';

interface Booking {
  id: string;
  bookingNo: string;
  serviceName: string;
  bookingDate: string;
  timeSlot: string;
  status: string;
  queueTicket?: string;
  queuePosition?: number;
  estimatedWaitTime?: string;
  customerName: string;
  phoneNumber: string;
}

const loading = ref(false);
const bookings = ref<Booking[]>([]);
const total = ref(0);
const currentPage = ref(1);
const pageSize = ref(10);
const statusFilter = ref('');

const loadBookings = async () => {
  try {
    loading.value = true;
    const params = {
      page: currentPage.value,
      pageSize: pageSize.value,
      status: statusFilter.value,
    };

    const result = await getMyBookings(params);
    bookings.value = result.list || [];
    total.value = result.total || 0;
  } catch (error) {
    console.error('加载预约记录失败:', error);
    message.error('加载预约记录失败');
    // 确保在错误时也初始化数据
    bookings.value = [];
    total.value = 0;
  } finally {
    loading.value = false;
  }
};

const takeQueueTicket = async (booking: Booking) => {
  try {
    const result = await takeQueueTicketApi(booking.id);
    message.success('取号成功！');
    loadBookings(); // 重新加载数据
  } catch (error) {
    console.error('取号失败:', error);
    message.error('取号失败，请重试');
  }
};

const cancelBooking = (booking: Booking) => {
  Modal.confirm({
    title: '确认取消预约',
    content: `确定要取消预约"${booking.serviceName}"吗？`,
    onOk: async () => {
      try {
        await cancelBookingApi(booking.id);
        message.success('预约已取消');
        loadBookings();
      } catch (error) {
        console.error('取消预约失败:', error);
        message.error('取消预约失败');
      }
    },
  });
};

const viewQueueStatus = (booking: Booking) => {
  // 跳转到排队状态页面
  console.log('查看排队状态:', booking);
};

const handlePageChange = (page: number) => {
  currentPage.value = page;
  loadBookings();
};

const handlePageSizeChange = (current: number, size: number) => {
  currentPage.value = 1;
  pageSize.value = size;
  loadBookings();
};

const formatDate = (date: string) => {
  return dayjs(date).format('YYYY-MM-DD');
};

const getStatusClass = (status: string) => {
  const classMap: Record<string, string> = {
    PENDING: 'status-pending',
    CONFIRMED: 'status-confirmed',
    IN_PROGRESS: 'status-in-progress',
    COMPLETED: 'status-completed',
    CANCELLED: 'status-cancelled',
  };
  return classMap[status] || 'status-pending';
};

const getStatusColor = (status: string) => {
  const colorMap: Record<string, string> = {
    PENDING: 'orange',
    CONFIRMED: 'blue',
    IN_PROGRESS: 'green',
    COMPLETED: 'default',
    CANCELLED: 'red',
  };
  return colorMap[status] || 'default';
};

const getStatusText = (status: string) => {
  const textMap: Record<string, string> = {
    PENDING: '待确认',
    CONFIRMED: '已确认',
    IN_PROGRESS: '进行中',
    COMPLETED: '已完成',
    CANCELLED: '已取消',
  };
  return textMap[status] || '未知状态';
};

onMounted(() => {
  loadBookings();
});
</script>

<template>
  <div class="my-bookings">
    <div class="bookings-header">
      <h3 class="title">我的预约记录</h3>
      <div class="filters">
        <Select
          v-model="statusFilter"
          placeholder="状态筛选"
          style="width: 120px"
          @change="loadBookings"
        >
          <SelectOption value="">全部</SelectOption>
          <SelectOption value="PENDING">待确认</SelectOption>
          <SelectOption value="CONFIRMED">已确认</SelectOption>
          <SelectOption value="IN_PROGRESS">进行中</SelectOption>
          <SelectOption value="COMPLETED">已完成</SelectOption>
          <SelectOption value="CANCELLED">已取消</SelectOption>
        </Select>
        <Button @click="loadBookings" :loading="loading">
          <IconifyIcon icon="mdi:refresh" />
        </Button>
      </div>
    </div>

    <div v-if="loading" class="loading-state">
      <Spin size="large" />
      <p>加载中...</p>
    </div>

    <div v-else-if="bookings.length === 0" class="empty-state">
      <IconifyIcon icon="mdi:calendar-blank" />
      <p class="empty-text">暂无预约记录</p>
    </div>

    <div v-else class="bookings-list">
      <div
        v-for="booking in bookings"
        :key="booking.id"
        class="booking-card"
        :class="getStatusClass(booking.status)"
      >
        <div class="booking-header">
          <div class="booking-info">
            <h4 class="service-name">{{ booking.serviceName }}</h4>
            <p class="booking-time">
              {{ formatDate(booking.bookingDate) }} {{ booking.timeSlot }}
            </p>
          </div>
          <div class="booking-status">
            <Tag :color="getStatusColor(booking.status)">
              {{ getStatusText(booking.status) }}
            </Tag>
          </div>
        </div>

        <div class="booking-details">
          <div class="detail-item">
            <span class="label">预约号：</span>
            <span class="value">{{ booking.bookingNo }}</span>
          </div>
          <div class="detail-item">
            <span class="label">取号：</span>
            <span class="value queue-number">{{
              booking.queueTicket || '未取号'
            }}</span>
          </div>
          <div class="detail-item">
            <span class="label">排队位置：</span>
            <span class="value">{{ booking.queuePosition || '未排队' }}</span>
          </div>
          <div class="detail-item">
            <span class="label">预计等待：</span>
            <span class="value">{{ booking.estimatedWaitTime || '--' }}</span>
          </div>
        </div>

        <div class="booking-actions">
          <Button
            v-if="booking.status === 'CONFIRMED' && !booking.queueTicket"
            type="primary"
            size="small"
            @click="takeQueueTicket(booking)"
          >
            取号排队
          </Button>
          <Button
            v-if="booking.status === 'PENDING'"
            type="default"
            size="small"
            @click="cancelBooking(booking)"
          >
            取消预约
          </Button>
          <Button
            v-if="booking.queueTicket"
            type="link"
            size="small"
            @click="viewQueueStatus(booking)"
          >
            查看排队状态
          </Button>
        </div>
      </div>
    </div>

    <!-- 分页 -->
    <div v-if="total > 0" class="pagination-wrapper">
      <Pagination
        v-model="currentPage"
        :page-size="pageSize"
        :total="total"
        :show-size-changer="true"
        :show-quick-jumper="true"
        @change="handlePageChange"
        @show-size-change="handlePageSizeChange"
      />
    </div>
  </div>
</template>

<style scoped>
.my-bookings {
  width: 100%;
}

.bookings-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 24px;
}

.title {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #1f2937;
}

.filters {
  display: flex;
  gap: 12px;
  align-items: center;
}

.loading-state,
.empty-state {
  padding: 60px 20px;
  color: #6b7280;
  text-align: center;
}

.empty-icon {
  margin-bottom: 16px;
  opacity: 0.5;
}

.empty-text {
  margin: 0;
  font-size: 16px;
}

.bookings-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.booking-card {
  padding: 20px;
  background: white;
  border: 1px solid #e5e7eb;
  border-radius: 12px;
  transition: all 0.3s ease;
}

.booking-card:hover {
  box-shadow: 0 4px 12px rgb(0 0 0 / 10%);
}

.booking-header {
  display: flex;
  align-items: flex-start;
  justify-content: space-between;
  margin-bottom: 16px;
}

.service-name {
  margin: 0 0 4px;
  font-size: 16px;
  font-weight: 600;
  color: #1f2937;
}

.booking-time {
  margin: 0;
  font-size: 14px;
  color: #6b7280;
}

.booking-details {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 12px;
  margin-bottom: 16px;
}

.detail-item {
  display: flex;
  align-items: center;
}

.detail-item .label {
  margin-right: 8px;
  font-size: 14px;
  color: #6b7280;
}

.detail-item .value {
  font-weight: 500;
  color: #1f2937;
}

.detail-item .value.queue-number {
  font-weight: 600;
  color: #3b82f6;
}

.booking-actions {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.pagination-wrapper {
  display: flex;
  justify-content: center;
  margin-top: 32px;
}

/* 状态样式 */
.status-pending {
  border-left: 4px solid #f59e0b;
}

.status-confirmed {
  border-left: 4px solid #3b82f6;
}

.status-in-progress {
  border-left: 4px solid #10b981;
}

.status-completed {
  border-left: 4px solid #6b7280;
}

.status-cancelled {
  border-left: 4px solid #ef4444;
}
</style>
